#!/usr/bin/env python
# -*- coding: utf-8 -*-
from stemmer import Stemmer
from databaseManager import DBManager
from cosine import cosine_distance
import operator
from mediawiki.wiki import wiki2html
# from markdown import Markdown

stemmerObj = Stemmer()

class Process:
    def flatten_count(self, iterable, element):
        count = 0
        for item in iterable:
            if item == element:
                count += 1
            if isinstance(item, list):
                count += self.flatten_count(item, element)
        return count
    
    def run(self, queryString=""):
        stemmedQueryStringsList = stemmerObj.stemming(queryString, False)
        
        dbManager = DBManager()
        documentsMap = dbManager.getDocAndWordsNR(stemmedQueryStringsList)
        if documentsMap == None:
            return "No result!"
        
        #text = ""
        #if documentsMap:
        #    for k, v in documentsMap.items():
        #        text = dbManager.getTextByID(k)
        occurancyMap = {}
        result = []
        if len(stemmedQueryStringsList) == 1:
            sortedCosMap = sorted(documentsMap.iteritems(), key=operator.itemgetter(1))
            sortedCosMap.reverse()
            resultStr = ""
            for docID,v in sortedCosMap:
                docTitle = dbManager.getTitleByDocID(docID)
                resultStr += "<a href='/%s'><div class='titleDiv'>%s</div></a>" % (docID, docTitle)
            return resultStr
        else:
            cosMap = {}
            for k, v in documentsMap.items():   
                q = [1] * len(v)
                zeros = self.flatten_count(v, 0)
                occurancyMap[k] = zeros
                print str(k) + " " + str(zeros) 
                  
            occurancyMap = sorted(occurancyMap.iteritems(), key=operator.itemgetter(1))
#             occurancyMap.reverse()    
            
            zo = 0
            for o in occurancyMap:
                if (zo != o[1]):
                    zo = o[1]
                    sortedCosMap = sorted(cosMap.iteritems(), key=operator.itemgetter(1))
                    sortedCosMap.reverse()
                    result.append(sortedCosMap)
                    cosMap.clear()
                cos = cosine_distance(q, documentsMap[o[0]])
                cosMap[o[0]] = cos
            
            sortedCosMap = sorted(cosMap.iteritems(), key=operator.itemgetter(1))
            sortedCosMap.reverse()
        result.append(sortedCosMap)
                
        resultStr = ""
        for r in result:
            for docID,v in r:
                docTitle = dbManager.getTitleByDocID(docID)
                resultStr += "<a href='/%s'><div class='titleDiv'>%s</div></a>" % (docID, docTitle)
       
        #return "The string is processed: " + dbManager.sqlTest(stemmedQueryString)
        
        #result = ""
        #for k, v in documentsMap.items():
        #    result += str(k) + " " + str(v)   
        #return str(documentsMap)
        
        #print unescaped
        return resultStr
    
    def getDoc(self, docID=""):
        if docID == "":
            return "<h1>Document not found</h1>"
        dbManager = DBManager()
        text = dbManager.getTextByID(docID)
#         markdown = Markdown()
#         text = markdown.convert(text.decode('utf-8'))
        return wiki2html(text, True)
#         return markdowner.convert(text.decode('utf-8'))
        
